﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Pixysoft.Framework.Configurations.Core
{
    class HtmlTable : IHtmlTable
    {
        string parentpath;

        int nestLevel = 0;

        int tableIndex = 0;

        IHtmlNode node;

        public HtmlTable(IHtmlNode node, string parentpath, int nestLevel, int tableIndex)
        {
            this.parentpath = parentpath;
            this.nestLevel = nestLevel;
            this.tableIndex = tableIndex;
            this.node = node;
        }

        public string ParentPath
        {
            get { return parentpath; }
        }

        public int NestLevel
        {
            get { return nestLevel; }
        }

        public int TableIndex
        {
            get { return tableIndex; }
        }

        public string Content
        {
            get { return node.Serialize(true); }
        }

        public IHtmlRow[] Rows
        {
            get
            {
                List<IHtmlRow> rows = new List<IHtmlRow>();

                foreach (IHtmlNode subnode in node.Nodes)
                {
                    if (!string.Equals(subnode.ElementName, "tr", StringComparison.OrdinalIgnoreCase))
                        continue;

                    rows.Add(new HtmlRow(subnode, parentpath, nestLevel, tableIndex, rows.Count));
                }

                return rows.ToArray();
            }
        }

        public string Serialize()
        {
            FormatStringBuilder builder = new FormatStringBuilder();
            for (int i = 0; i < nestLevel * 3; i++)
                builder.Indent();
            builder.AppendLine(string.Format("<table path='{0}{1}' nest='{2}'>", parentpath, tableIndex, nestLevel));
            foreach (IHtmlRow row in Rows)
            {
                builder.Append(row.Serialize());
            }
            builder.AppendLine("</table>");
            for (int i = 0; i < nestLevel * 3; i++)
                builder.Outdent();
            return builder.ToString();
        }

        public IHtmlNode HtmlNode
        {
            get { return node; }
        }
    }
}
